package com.zxd.auth.controller;

import com.zxd.auth.config.OAuth2ClientProperties;
import com.zxd.auth.service.OAuth2ClientService;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthAlipayRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWeiboRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * OAuth2授权回调接口
 */
@Slf4j
@RestController
@RequestMapping("login/oauth2")
public class OAuth2Controller {

    @Autowired
    private OAuth2ClientService auth2ClientService;

    /** 创建授权request */
    private AuthRequest getAuthRequest(String source) {
        OAuth2ClientProperties.OAuth2Client client = auth2ClientService.getOneClient(source);
        if (source.equals("weibo")) {
            return new AuthWeiboRequest(AuthConfig.builder()
                .clientId(client.getClientId())
                .clientSecret(client.getClientSecret())
                .redirectUri(client.getRedirectUri() + source)
                .build());
        } else if (source.equals("alipay")) {
            return new AuthAlipayRequest(AuthConfig.builder()
                    .clientId(client.getClientId())
                    .clientSecret(client.getClientSecret())
                    .redirectUri(client.getRedirectUri() + source)
                    .build(),
                    client.getPublicKey());
        } else {
            return null;
        }
    }

    /**
     * 构建授权页面
     * 实际上可以前端构建
     * @param source 第三方授权平台
     */
    @GetMapping("/render/{source}")
    public void renderAuth(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
        // 生成授权页面
        AuthRequest authRequest = this.getAuthRequest(source);
        authRequest.authorize("state");
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        response.sendRedirect(authorizeUrl);
    }

    /**
     * Auth2服务端的回调，获取访问令牌，再获取用户信息
     * @param source 第三方授权平台
     */
    @RequestMapping("/callback/{source}")
    public Object login(@PathVariable("source") String source, AuthCallback callback) {
        AuthRequest authRequest = this.getAuthRequest(source);
        AuthResponse response = authRequest.login(callback);
        return response;
    }
}
